package com.hyh.ad.common.utils;

import cn.hutool.core.util.RandomUtil;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;


import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

public class PhoneUtil {
    /**
     * 发送短信
     * @param  phone
     * @return  String
     */
    //private static String accessKeyId ="LTAI5tFHASJjq5vtSTgx7i5H";

    //private static String accessKeySecret = "AGxWoYiyq8beX8VehzIHzkOYxw0w0p";

    //private static String sign = "Titk购物";

    //private static String templateCode = "SMS_465333275";


    //聂进东的key
    private static String accessKeyId ="LTAI5tF3qiZVn1AmsDPmfJHS";

    private static String accessKeySecret = "VUJBZm5tf1euFX6wwL0HGxswEc3BfJ";

    private static String sign = "基础框架服务";

    private static String templateCode = "SMS_468945565";

    private static final long TIME_LIMIT = TimeUnit.SECONDS.toMillis(30); // 发送频率限制，1分钟

    private static final Map<String, Long> lastSentTime = new HashMap<>(); // 记录每个号码的最后发送时间

    public static String send(String phone, String key){
        // 限制发送频率
        long currentTime = System.currentTimeMillis();
        if (lastSentTime.containsKey(phone) && (currentTime - lastSentTime.get(phone)) < TIME_LIMIT) {
            throw new RuntimeException("发送频率过高，请稍后再试");
        }
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = getCommonRequest(phone, key);
        try {
            CommonResponse response = client.getCommonResponse(request);
            lastSentTime.put(phone, currentTime); // 记录发送时间
            return response.getData();
        } catch (ClientException e) {
            throw new RuntimeException(e);
        }
    }
    @NotNull
    private static CommonRequest getCommonRequest(String phone, String key) {
        CommonRequest request = new CommonRequest();//组装请求对象
        request.setMethod(MethodType.POST);//设置post提交
        request.setDomain("dysmsapi.aliyuncs.com");//短信API产品域名（接口地址固定，无需修改）
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", sign);//短信签名
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", "{code:"+ key +"}");
        return request;
    }
}
